package com.tan.lbs.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;


/**
 * 
 * Copyright by Zhensheng Tan only for Final Year Project Use.
 * Class description:Provide a singleton Database Connector to
 *  hide the procedure details in some DB transactions.
 * @author Zhensheng Tan 
 *
 */
public class JDBCUtil {

	private static JDBCUtil instance; 
	private Properties properties;
	private String url;
	private String userName;
	private String password;
	private String driver;
	private Connection conn = null;

	/**
	 * Private Constructor.
	 */
	private JDBCUtil() {
		this.init();
	}

	/**
	 * Singleton pattern, only allow one DBManager class in runtime.
	 * 
	 * @return DBConnectionManager
	 */
	public static synchronized JDBCUtil getInstance() {
		if (instance == null) {
			instance = new JDBCUtil();
		}
		return instance;
	}

	/**
	 * Initialization.
	 */
	private void init() {
		try {
			properties = new Properties();
			properties.load(getClass().getResourceAsStream( "db.properties")); 
			driver = properties.getProperty("driver");
			if (driver != null)
		    	Class.forName(driver);  
			url = properties.getProperty("url");
			userName = properties.getProperty("username");
			password = properties.getProperty("password");

		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("Cannot read the properties file.");
			return;
		}

	}

	/**
	 * Return a Connection from Database.
	 * 
	 * @param name
	 *           
	 * @return Connection
	 */
	public Connection getConnection() {
		Connection con = null;
		try {
			con = DriverManager.getConnection(url, userName, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;
	}
	
	/**
	 * After using the DB, close the connection safely.
	 */
	public void closeConnection() {
		try {
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
